import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Popconfirm, Button, Divider, Dropdown, Menu, message, Input } from 'antd';
import React, { useState, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { Search } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { queryRule, updateRule, addRule, removeRule } from './service';
import { Redirect } from "react-router";
import { ConfigProvider } from 'antd';
import enUS from 'antd/es/locale/en_US';


const handleQuery = async fields => {
  const hide = message.loading('Querying');

  try {
    await queryRule({ ...fields });
    hide();
    message.success('Queried successfully');
    return true;
  } catch (error) {
    hide();
    message.error(error.data);
    return false;
  }
};

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async fields => {
  const hide = message.loading('Adding');

  try {
    await addRule({ ...fields });
    hide();
    message.success('Added successfully');
    return true;
  } catch (error) {
    hide();
    message.error(error.toString());
    return false;
  }
};
/**
 * 更新节点
 * @param fields
 */

const handleUpdate = async fields => {
  const hide = message.loading('Editing');

  try {
    await updateRule({
      description: fields.description,
      id: fields.id,
    });
    hide();
    message.success('Edited successfully');
    return true;
  } catch (error) {
    hide();
    message.error(error.toString());
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */

const handleDelete = async key => {
  const hide = message.loading('Deleting');
  if (!key) return true;

  try {
    await removeRule({
      id: key, 
    }); 
    hide();
    message.success('Deleted successfully, refreshing');

    return true;
  } catch (error) {
    hide();
    message.error('Deleted failed, please retry');
    return false;
  }
  
 
};

const handleRemove = async selectedRows => {
  const hide = message.loading('Deleting');
  if (!selectedRows) return true;

  try {
    await removeRule({
      key: selectedRows.map(row => row.key),
    });
    hide();
    message.success('Deleted successfully, refreshing');
    return true;
  } catch (error) {
    hide();
    message.error('Deleted failed, please retry');
    return false;
  }
};

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef();

  const validateIP = (rule, value, callback) => {
    var reg=/^((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9]))$/
    if (!value) {
      callback()
    }else if (!reg.test(value)) {
      callback("Please enter a valid format IP Address.")
    }else {
      callback()
    }
  }

  const columns = [
    {
      title: 'Storage Type',
      dataIndex: 'storage_type',
      initialValue: "brocade",
      hideInTable: true,
      hideInSearch: true,
      hideInForm: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Input placeholder="please input..."  />;
      },
    }, 
    {
      title: 'Management IP',
      dataIndex: 'ip',
      rules: [
        {
          required: true,
          message: 'Management IP is required',
        },
        {
          validator: validateIP
        },
      ],
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Input placeholder="please input..."  />;
      },
    },
    {
      title: 'User',
      dataIndex: 'user',
      rules: [
        {
          required: true,
          message: 'User is required',
        },
      ],
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Input placeholder="please input..."  />;
      },
    },
    {
      title: 'Password',
      dataIndex: 'password',
      type: 'password',
      hideInSearch: true,
      hideInTable: true,
      rules: [
        {
          required: true,
          message: 'Password is required',
        },
      ],
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Input.Password  placeholder="please input"  />;
      },
    },
    { 
      title: 'Exporter Port',
      dataIndex: 'exporter_port',
      hideInForm: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Input placeholder="please input..."  />;
      },
    },
    {
      title: 'Description',
      dataIndex: 'description',
      valueType: 'textarea',
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Input placeholder="please input..."  />;
      },
    },
    {
      title: 'Operation',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record, index, action) => (
          <>
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}
          >
            Edit
          </a>
          <Divider type="vertical" />
          <a href="/brocade/detail">Detail</a>
          <Divider type="vertical" />
          <Popconfirm title="Sure to delete?" onConfirm={() => { handleDelete(record.id); action.reload(); }}>
            <a>Delete</a>
          </Popconfirm> 
          </> 
     ),

    },
  ];
  return (
    <ConfigProvider locale={enUS}>
    <PageHeaderWrapper>
       
     <ProTable
        headerTitle="Search"
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={(action, { selectedRows }) => [
          <Button type="primary" onClick={() => handleModalVisible(true)}>
            <PlusOutlined/> New
          </Button>
        ]}
        tableAlertRender={({ selectedRowKeys, selectedRows }) => (
          <div>
            Selected{' '}
            <a
              style={{
                fontWeight: 600,
              }}
            >
              {selectedRowKeys.length}
            </a>{' '}
            items &nbsp;&nbsp;
          </div>
        )}
        search={  
          {
            resetText:'Reset',
            searchText:"search",
            collapsed:false,
            collapseRender:()=>false
          }
        }
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        // request={(params, sorter, filter) => {
        //     const success = handleQuery({ ...params, sorter, filter })
        //     if (!success) {
        //         message.error("abc")
        //     }  
        // }}
        columns={columns}
        rowSelection={{}}
      />
      <CreateForm onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable
          onSubmit={async value => {
            const success = await handleAdd(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          type="form"
          columns={columns}
          rowSelection={{}}
        />
      </CreateForm>

      {stepFormValues && Object.keys(stepFormValues).length ? (
        <UpdateForm
          onSubmit={async value => {
            const success = await handleUpdate(value);

            if (success) {
              handleUpdateModalVisible(false);
              setStepFormValues({});

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
        />
      ) : null}
    
    </PageHeaderWrapper>
    </ConfigProvider> 
  );
};

export default TableList;
